package top.lshaci.learning.thread;

import java.util.concurrent.*;

/**
 * CompletableFutureTest
 *
 * @author lshaci
 * @since 1.0.0
 */
public class CompletableFutureTest1 {

    static ExecutorService executorService = Executors.newFixedThreadPool(4);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();
        CompletableFuture<String> searchImg = CompletableFuture.supplyAsync(() -> {
            System.err.println("查询图片。。。开始");
            try {
                TimeUnit.MILLISECONDS.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                System.err.println("查询图片。。。完成");
            }
            return "hello.jpg";
        }, executorService);
        CompletableFuture<String> searchAtt = CompletableFuture.supplyAsync(() -> {
            System.err.println("查询属性。。。开始");
            try {
                TimeUnit.MILLISECONDS.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                System.err.println("查询属性。。。完成");
            }
            return "5G";
        }, executorService);
        CompletableFuture<String> searchBrand = CompletableFuture.supplyAsync(() -> {
            System.err.println("查询品牌。。。开始");
            try {
                TimeUnit.MILLISECONDS.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                System.err.println("查询品牌。。。完成");
            }
            return "华为";
        }, executorService);

//        CompletableFuture<Void> future = CompletableFuture.allOf(searchImg, searchAtt, searchBrand);
//        future.get();
//
//        System.err.println("花费时间：" + (System.currentTimeMillis() - start) + "ms");
//        System.err.println("商品图片：" + searchImg.get());
//        System.err.println("商品品牌：" + searchBrand.get());
//        System.err.println("商品属性：" + searchAtt.get());

        CompletableFuture<Object> future = CompletableFuture.anyOf(searchImg, searchAtt, searchBrand);
        future.get();

        System.err.println("花费时间：" + (System.currentTimeMillis() - start) + "ms");
        System.err.println("最先返回的结果：" + future.get());

    }
}
